package com.wgs.sentinel.configuration;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * Copyright(c)2015-2025, xxxxxxxxx有限公司
 * All rights reserved.
 * <p>
 * 项目名称:ch1_sentineldemo
 * 文件名称:ServiceBlockExceptionHandler
 *
 * @author ygp   自定义更改流控默认提示语
 * @create 2022-7-25 17:33
 */
@Component
public class ServiceBlockExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
        //设置响应数据编码
        httpServletResponse.setCharacterEncoding("utf-8");
        //告诉客户端响应数据类型以及客户端显示的编码
        httpServletResponse.setContentType("text/html;charset=utf-8");
        //创建Map来存储要返回的数据
        Map<String,Object> map = new HashMap<>();
        map.put("status", 429);
        map.put("message", "服务器忙,请稍后访问...");
        //输出
        String jsonStr = new ObjectMapper().writeValueAsString(map);
        PrintWriter out = httpServletResponse.getWriter();
        out.print(jsonStr);
        out.flush();
        out.close();
    }
}
